<?php

namespace app\admin\controller;

use addons\wechat\library\Wechat;
use app\common\controller\Backend;
use fast\Http;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 班级排课管理
 *
 * @icon fa fa-circle-o
 */
class SchoolClassSubjectSchedule extends Backend
{

    /**
     * SchoolClassSubjectSchedule模型对象
     * @var \app\admin\model\SchoolClassSubjectSchedule
     */
    protected $model = null;
    public $wbeet = [
        '星期天' => 0,
        '星期一' => 1,
        '星期二' => 2,
        '星期三' => 3,
        '星期四' => 4,
        '星期五' => 5,
        '星期六' => 6,
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SchoolClassSubjectSchedule;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $xiaobao = $this->selectpage();
                $xiabao2 = $xiaobao->getData();
                foreach ($xiabao2['list'] as $k => $v) {
                    $school_class_subject = db('school_class_subject')->alias('a')->field('a.*,b.subject_name')->join('school_subject b', 'a.subject_id = b.id')->where('a.id', $v['class_subject_id'])->find();
                    $school_class_subject_schedule = db('school_class_subject_schedule')->where('id', $v['id'])->find();
                    $name = $school_class_subject['subject_name'] . '(' . $school_class_subject_schedule['date'] . ' ' . $school_class_subject_schedule['time_slot'] . ')';
                    $xiabao2['list'][$k]['class_subject_id'] = $name;
                }
                return json($xiabao2);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $class_subject_id = input('ids');
            $subject_where = [];
            if ($class_subject_id) {
                $subject_where['class_subject_id'] = $class_subject_id;
            }
            $total = $this->model
                ->where($where)
                ->where($subject_where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($subject_where)
                ->order('id')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['id', 'date', 'time_slot', 'status', 'createtime']);

            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $class_subject_id = $this->request->request('ids');
        $class_id = $this->request->request('class_id');
        $this->assignconfig('class_subject_id', $class_subject_id);
        $this->assignconfig('class_id', $class_id);
        $subject = db('school_class_subject_schedule')->where('class_id', $class_id)->where('status', '1')->count();
        $this->assign('subject', $subject);
        $this->assignconfig('subject', $subject);
        return $this->view->fetch();
    }

    /**
     * 排课
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add(){



        if ($this->request->isPost()) {
            //1.前端以row命名传过来的数组。2.post('row/a'); 获取post提交的以row命名的数据，/a的作用是强制转换为数组
            $params = $this->request->post("row/a");


            $event = json_decode($params['event'], 1);

            $school_class_subject = db('school_class_subject')->where('id', $params['class_subject_id'])->find();
            $status = db('school_class')->where('id', $params['class_id'])->find();
            $i = $school_class_subject['total_class_hour'];
            $w_id = [];
            $a = 0;
            foreach ($event as $k => $v) {
                if ($v['time_slot']) {
                    $w_id[] = $this->wbeet[$v['w_id']];
                    $time_slot[$this->wbeet[$v['w_id']]] = explode(',', $v['time_slot']);
                }
            }
            while ($i) {
                $times = $status['start_time'] + (60 * 60 * 24 * $a);
                $a++;
                $time = date("w", $times);
                if (in_array($time, $w_id)) {
                    foreach ($time_slot[$time] as $vs) {
                        $time_slots = db('school_schedule_time')->where('id', $vs)->find();
                        $data[] = [
                            'csmmeet_room_id' => $status['csmmeet_room_id'],
                            'class_subject_id' => $params['class_subject_id'],
                            'class_id' => $params['class_id'],
                            'date' => date('Y-m-d', $times),
                            'time_id' => $vs,
                            'time_slot' => $time_slots['start_date'],
                            'createtime' => time(),
                            'admin_id' => $status['admin_id'],
                        ];
                        $i--;
                        if ($i == 0) {
                            break;
                        }
                    }
                }
            }
            $this->model->insertAll($data);
            $this->success('成功');
    }
        $class_subject_id = $this->request->request('class_subject_id');
        $class_id = $this->request->request('class_id');
        $list = $this->weeb();
        $this->assign('list', $list);
        $this->assign('class_subject_id', $class_subject_id);
        $this->assign('class_id', $class_id);
        return $this->view->fetch();
    }

    public function weeb()
    {
        $data = [];
        $data[] = [
            'id' => 0,
            'name' => '星期天',
        ];
        $data[] = [
            'id' => 1,
            'name' => '星期一',
        ];
        $data[] = [
            'id' => 2,
            'name' => '星期二',
        ];
        $data[] = [
            'id' => 3,
            'name' => '星期三',
        ];
        $data[] = [
            'id' => 4,
            'name' => '星期四',
        ];
        $data[] = [
            'id' => 5,
            'name' => '星期五',
        ];
        $data[] = [
            'id' => 6,
            'name' => '星期六',
        ];
        return $data;
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);
                $result = false;
                $school_schedule_time = db('school_schedule_time')->where('id', $params['time_slot'])->find();
                $params['time_id'] = $params['time_slot'];
                $params['time_slot'] = $school_schedule_time['start_date'];
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 调课
     */
    public function tiaoke()
    {
        $ids = $this->request->request('ids');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $model_info = db('school_class_subject_schedule')->where('id', $ids)->find();
            $id = $model_info['id'];
            $school_schedule_time = db('school_schedule_time')->where('id', $params['time_slot'])->find();
            $start_date = explode('-', $school_schedule_time['start_date']);
            $model_infodate = $model_info['date'];
            $model_infotime_slot = $model_info['time_slot'];
            try {
                if (strtotime($params['date'] . ' ' . $start_date[0]) > time() && $model_info['status'] != 1) {
                    Db::startTrans();
                    db('school_class_subject_schedule')->where('id', $id)->update(['status' => '2', 'transfer_remarks' => $params['transfer_remarks']]);
                    unset($model_info['id']);
                    $model_info['admin_id'] = $params['admin_id'];
                    $model_info['date'] = $params['date'];
                    $model_info['time_id'] = $params['time_slot'];
                    $model_info['time_slot'] = $school_schedule_time['start_date'];
                    $model_info['createtime'] = time();
                    $model_info['status'] = '0';



                    $transfer_id = db('school_class_subject_schedule')->insertGetId($model_info);
                    db('school_class_subject_schedule')->where('id', $id)->update(['transfer_id' => $transfer_id, 'is_notice' => '1']);
                    Db::commit();
                    $subject = db('school_class_subject')->alias('a')
                        ->field('a.*,b.subject_name')
                        ->join('ed_school_subject b', 'a.subject_id = b.id')
                        ->where('a.class_id', $model_info['class_id'])
                        ->find();
                    $calss_user = db('school_calss_user')
                        ->alias('a')
                        ->field('b.*,c.nickname')
                        ->join('ed_third b', 'b.user_id = a.user_id', 'right')
                        ->join('ed_user c', 'c.id = b.user_id', 'left')
                        ->where('a.class_id', $model_info['class_id'])
                        ->where('a.status', '0')
                        ->select();
                    $admin_third = db('third')->where('admin_id', $model_info['admin_id'])->find();
                    $this->send($admin_third['openid'], $subject['subject_name'], ($model_infodate . ' ' . $model_infotime_slot), ($params['date'] . ' ' . $school_schedule_time['start_date']), $params['transfer_remarks']);
                    foreach ($calss_user as $vv) {
                        $this->send($vv['openid'], $subject['subject_name'], ($model_infodate . ' ' . $model_infotime_slot), ($params['date'] . ' ' . $school_schedule_time['start_date']), $params['transfer_remarks']);
                    }
                    throw new \Exception('成功', 1);
                } else {
                    throw new \Exception('状态不正确或者调课时间错误');
                }
            } catch (\Exception $e) {
                //如获取到异常信息，对所有表的删、改、写操作，都会回滚至操作前的状态：
                if ($e->getCode() == 0) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } else {
                    $this->success($e->getMessage());
                }


            }
        }
        $info_class = $this->model->where('id', $ids)->find();
        $info = $this->model->where('class_id', $info_class['class_id'])->order('date', 'desc')->find();
        $w = db('school_class_subject_schedule')->query("select FROM_UNIXTIME(UNIX_TIMESTAMP(date),'%w') as w from ed_school_class_subject_schedule where class_id = {$info_class['class_id']} GROUP BY w ORDER BY w");
        $w = array_column($w, 'w');
        //$d_w = date('w', strtotime($info['date']));
        for ($i = 1; $i <= 7; $i++) {
            if (in_array(date('w', strtotime("+{$i} day", strtotime($info['date']))), $w)) {
                $date = date('Y-m-d', strtotime("+{$i} day", strtotime($info['date'])));
                break;
            }
        }
        $this->assign('date', $date);
        $this->assign('info_class', $info_class);
        return $this->fetch();
    }

    /**
     * @param $touser open_id
     * @param $keyword1 课程名
     * @param $keyword2 原上课时间
     * @param $keyword3 现在上课时间
     * $keyword4 调课原因
     * @return array
     */
    public function send($touser, $keyword1, $keyword2, $keyword3, $keyword4)
    {
        $token = Wechat::getAccessToken();
        if (!$token) {
            return;
            //$this->error("发送失败，请稍后重试");
        }

        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $token;
        $params = [
            'touser' => $touser,
            'template_id' => 'uH1cE_k-VxSbDrsgH3ilVtTQ7pxggH-py7oO7cdBpZc',
            'data' => [
                'first' => ['value' => '你好，以下课程将进行调课', 'color' => '#173177'],
                'keyword1' => ['value' => $keyword1, 'color' => '#173177'],
                'keyword2' => ['value' => $keyword2, 'color' => '#173177'],
                'keyword3' => ['value' => $keyword3, 'color' => '#173177'],
                'keyword4' => ['value' => $keyword4, 'color' => '#173177'],
                'remark' => ['value' => '若因故无法参加，请及时联系老师', 'color' => '#173177']
            ]
        ];

        return $result = Http::sendRequest($url, json_encode($params));
    }
}
